<template>
  <div class="register-container">
    <!-- 顶部背景 -->
    <div class="register-header">
      <van-icon name="arrow-left" class="back-icon" @click="goBack" />
      <div class="welcome-text">欢迎注册</div>
      <div class="sub-title">请完善个人信息</div>
    </div>

    <!-- 注册表单 -->
    <div class="register-form">
      <!-- 姓名输入框 -->
      <van-field
        v-model="formData.name"
        placeholder="请输入姓名"
        label="姓名"
        class="input-field"
        :rules="[
          { required: true, message: '请输入姓名' },
          {
            pattern: /^[\u4e00-\u9fa5a-zA-Z]{2,}$/,
            message: '姓名不能包含数字，且至少2个字符',
          },
        ]"
        autocomplete="off"
        @input="validateName"
      />

      <!-- 手机号输入框 -->
      <div class="phone-input">
        <van-field
          v-model="formData.phone"
          placeholder="请输入手机号"
          class="input-field"
          :rules="[
            {
              required: true,
              pattern: /^1[3-9]\d{9}$/,
              message: '请输入正确的手机号',
            },
          ]"
          autocomplete="off"
        >
          <template #label>
            <div class="area-code" @click="goToCountrySelect">
              {{ selectedCountry.code }}
              <van-icon name="arrow-down" />
            </div>
          </template>
        </van-field>
      </div>

      <!-- 账号输入框 -->
      <van-field
        v-model="formData.account"
        placeholder="请输入账号"
        label="账号"
        class="input-field"
        :rules="[{ required: true, message: '请输入账号' }]"
        autocomplete="off"
      />

      <!-- 密码输入框 -->
      <van-field
        v-model="formData.password"
        :type="showPassword ? 'text' : 'password'"
        placeholder="请输入密码"
        label="密码"
        class="input-field"
        :rules="[{ required: true, message: '请输入密码' }]"
        autocomplete="off"
      >
        <template #right-icon>
          <van-icon
            :name="showPassword ? 'eye-o' : 'closed-eye'"
            @click="showPassword = !showPassword"
          />
        </template>
      </van-field>

      <!-- 验证码输入框 -->
      <van-field
        v-model="formData.smsCode"
        center
        placeholder="请输入验证码"
        label=""
        class="input-field"
        autocomplete="off"
      >
        <template #button>
          <van-button
            size="small"
            class="send-code-btn"
            :disabled="countdown > 0"
            @click="sendCode"
          >
            {{ codeButtonText }}
          </van-button>
        </template>
      </van-field>

      <!-- 注册按钮 -->
      <div class="register-btn-wrapper">
        <van-button
          block
          class="register-btn"
          :loading="loading"
          @click="handleRegister"
        >
          注册
        </van-button>
        <!-- <img 
          src="@/assets/homeOther/register.png" 
          alt="注册" 
          class="register-btn-img" 
          @click="handleRegister"

        /> -->
      </div>
    </div>

    <!-- loading组件 -->
    <div v-if="loading" class="loading-wrapper">
      <van-loading
        type="spinner"
        color="#1989fa"
        size="40px"
        text="加载中..."
        vertical
      >
        加载中...</van-loading
      >
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, onUnmounted } from "vue";
import { showToast } from "vant";
import { useRouter } from "vue-router";
import countriesData from "@/data/countries.json";
import { register, sendSmsCode } from "@/api/index";
import { storage } from "@/utils/storage";
import type { RegisterParams } from "@/types";

// 定义国家类型
interface Country {
  name: string;
  code: string;
  countryCode: string;
  flag: string;
}

// 路由实例
const router = useRouter();

// 表单数据
const formData = reactive<RegisterParams>({
  name: "",
  phone: "",
  smsCode: "",
  account: "",
  password: "",
});

// 状态变量
const loading = ref(false);
const countdown = ref(0);
const codeButtonText = ref("获取验证码");
const showPassword = ref(false);
let timer: number | null = null;

// 国家选择相关
const countries = ref(countriesData);
const selectedCountry = ref(countries.value[0]); // 默认选择中国

// 返回上一页
const goBack = () => {
  router.back();
};

// 跳转到国家选择页面
const goToCountrySelect = () => {
  // 存储当前选中的国家代码到sessionStorage
  sessionStorage.setItem(
    "selectedCountryCode",
    selectedCountry.value.countryCode
  );

  router.push({
    path: "/country-select",
    query: {
      from: "register",
    },
  });
};

// 监听路由返回，获取选择的国家
onMounted(() => {
  // 从路由参数中获取选择的国家
  const selectedCountryCode = router.currentRoute.value.query
    .selectedCountry as string;
  if (selectedCountryCode) {
    const country = countries.value.find(
      (c) => c.countryCode === selectedCountryCode
    );
    if (country) {
      selectedCountry.value = country;
    }
  }
});

// 发送验证码
const sendCode = async () => {
  // 如果正在倒计时中，直接返回
  if (countdown.value > 0) {
    return;
  }

  // 验证手机号
  if (!formData.phone) {
    showToast("请输入手机号");
    return;
  }

  // 根据选择的国家调整手机号验证规则
  if (
    selectedCountry.value.countryCode === "CN" &&
    !/^1[3-9]\d{9}$/.test(formData.phone)
  ) {
    showToast("请输入正确的手机号");
    return;
  }

  try {
    // 调用发送验证码API
    const response = await sendSmsCode({ phone: formData.phone });

    if (response.code === 0) {
      // 开始倒计时
      countdown.value = 60;
      codeButtonText.value = `${countdown.value}s`;

      // 设置倒计时
      timer = window.setInterval(() => {
        countdown.value--;
        codeButtonText.value = `${countdown.value}s`;

        if (countdown.value <= 0) {
          clearInterval(timer as number);
          codeButtonText.value = "获取验证码";
          countdown.value = 0; // 确保倒计时重置为0
        }
      }, 1000);

      showToast({ type: "success", message: response.msg || "验证码已发送" });
    } else {
      showToast(response.msg || "发送验证码失败");
    }
  } catch (error) {
    console.error("发送验证码失败:", error);
    showToast("发送验证码失败，请稍后重试");
  }
};

// 姓名输入验证
const validateName = (value: string) => {
  // 移除数字字符
  const filteredValue = value.replace(/[0-9]/g, "");
  if (filteredValue !== value) {
    formData.name = filteredValue;
    showToast("姓名不能包含数字");
  }
};

// 删除未使用的确认密码校验逻辑（避免类型错误）

// 处理注册
const handleRegister = async () => {
  // 表单验证
  if (!formData.name) {
    showToast("请输入姓名");
    return;
  }

  // 验证姓名格式
  if (!/^[\u4e00-\u9fa5a-zA-Z]{2,}$/.test(formData.name)) {
    showToast("姓名不能包含数字，且至少2个字符");
    return;
  }

  if (!formData.phone || !/^1[3-9]\d{9}$/.test(formData.phone)) {
    showToast("请输入正确的手机号");
    return;
  }

  if (!formData.smsCode) {
    showToast("请输入验证码");
    return;
  }

  // 验证账号
  if (!formData.account) {
    showToast("请输入账号");
    return;
  }

  // 验证密码
  if (!formData.password) {
    showToast("请输入密码");
    return;
  }

  // 开始注册
  try {
    loading.value = true;

    // 调用注册API
    const response = await register({
      ...formData,
    });

    // 检查返回结果
    if (response.code === 0) {
      // 先保存用户信息，这样后续保存 token 时会使用正确的 userId
      storage.setUserInfo(response.data);
      
      // 再保存 token
      if (response.data.accessToken) {
        storage.setItem("accessToken", response.data.accessToken);
      }
      if (response.data.refreshToken) {
        storage.setItem("refreshToken", response.data.refreshToken);
      }
      
      showToast({ type: "success", message: "注册成功" });
      // 直接跳转到首页
      router.replace("/home");
    } else {
      showToast(response.msg || "注册失败");
    }
  } catch (error) {
    console.error("注册失败:", error);
    showToast("注册失败，请稍后重试");
  } finally {
    loading.value = false;
  }
};

// 组件销毁时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer);
  }
});
</script>

<style lang="scss" scoped>
@import url("./style/index.scss");
</style>